//
//  PSSkiTrackingPlayer.m
//  PandaSkiing
//
//  Created by Felix Yin on 2018/1/3.
//  Copyright © 2018年 Felix. All rights reserved.
//

#import "PSSkiTrackingPlayer.h"
#import <AVFoundation/AVFoundation.h>

@interface PSSkiTrackingPlayer()

@property (nonatomic, assign) PSVoicePromptType voicePromptType;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) NSBundle *audioBundle;

@end

@implementation PSSkiTrackingPlayer

- (instancetype)init{
    self = [super init];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    //默认男声
    _voicePromptType = PSVoiceTypeMan;
    return self;
}



#pragma mark Logic Handle

- (void)updateVoiceTrackingType:(PSVoicePromptType)type{
    _voicePromptType = type;
}

//ski_background  ski_fallraise_finish  ski_pause  ski_skilift_start  ski_start
- (void)playAudio:(NSString *) str distance:(CGFloat)distance time:(NSInteger)time{
    BOOL result = YES;//[PSTools getBoolValue:SkiTrackingVoiceSwitchDefault]; //模式是开启语音
    BOOL result2 = YES;//[PSTools getBoolValue:SkiTrackingVoiceSwitch];
    BOOL result3 = result ? result2 : YES;

    if (!result3) {
        //关闭语音
        return;
    }
    
    if (str.length < 1) {
        return;
    }
    BOOL result4 = YES;//[PSTools getBoolValue:SkiTrackingVoiceSwitchType];
    NSString *prefix = result4 ? @"gril_" : @"man_";//(self.voicePromptType == PSVoiceTypeMan)
    NSString *name = [NSString stringWithFormat:@"%@%@",prefix,str];
    NSString *filePath =[self filePathWithName:name];
    [self playAudio:filePath];
}


- (void) playAudio:(NSString *) audioPath{
    if (audioPath)
    {
        NSURL *url = [NSURL fileURLWithPath:audioPath];
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        [self.audioPlayer prepareToPlay];
        [self.audioPlayer play];
    }
}



- (NSString *) filePathWithName:(NSString *) name{
    return [self.audioBundle pathForResource:name ofType:@"mp3"];
}


#pragma mark Lazy Loading

- (NSBundle *)audioBundle{
    if (!_audioBundle) {
        NSString *bundlePath = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"Audio.bundle"];
        NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
        _audioBundle = bundle;
    }
    return _audioBundle;
}

@end
